package cn.cttic.link.service.impl;

import cn.cttic.common.core.exception.link.LinkException;
import cn.cttic.link.api.domain.bo.BaseThirdInterfaceBo;
import cn.cttic.link.api.domain.bo.DeviceActiveBo;
import cn.cttic.link.api.domain.vo.DeviceActiveResultVo;
import cn.cttic.link.service.IBaseThirdInterfaceService;
import cn.cttic.link.service.IMapGooNoticeService;
import cn.cttic.order.api.RemoteInstallOrderService;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
@RequiredArgsConstructor
public class MapGooNoticeServiceImpl implements IMapGooNoticeService {

    private final IBaseThirdInterfaceService thirdInterfaceService;

    @DubboReference
    private RemoteInstallOrderService remoteInstallOrderService;

    @Override
    public DeviceActiveResultVo excuteNoticeAction(DeviceActiveBo bo) {
        log.info("[麦谷通知接口][开始]");
        log.info("[麦谷通知接口][参数] {}", JSON.toJSONString(bo));

        DeviceActiveResultVo vo = new DeviceActiveResultVo();

        BaseThirdInterfaceBo interfaceBo = new BaseThirdInterfaceBo();
        interfaceBo.setInterfaceType("MapGooNotice");
        interfaceBo.setAccessUrl("/link/mapgoo/notice");
        interfaceBo.setRequestType("POST");
        interfaceBo.setRequestBody(JSON.toJSONString(bo));

        vo.setImei(bo.getImei());
        vo.setActiveTime(LocalDateTime.now());
        vo.setSuccess(1);

        interfaceBo.setResponseBody(JSON.toJSONString(vo));
        if (!thirdInterfaceService.insertByBo(interfaceBo)) {
            throw new LinkException("录入接口数据失败");
        }

        try {
            remoteInstallOrderService.deviceActive(
                bo.getImei(),
                vo.getActiveTime(),
                bo.getFirstOnlineTime(),
                interfaceBo.getId()
            );
            log.info("[麦谷通知接口][激活完成]");
        } catch (Exception e) {
            log.error("[麦谷通知接口][激活完成]", e);
        }

        return vo;
    }
}
